package com.itbaizhan.config;

import com.itbaizhan.constant.Constant;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author spf
 * @date 2024/5/10
 * @time 14:34
 */
@Configuration
//@EnableResourceServer  会报错由于版本问题security
public class ResourceServerConfigure extends ResourceServerConfigurerAdapter {
    /**
     * 配置资源服务器向认证服务器发送请求，验证token
     *
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        ResourceServerSecurityConfigurer resourceServerSecurityConfigurer = resources.resourceId(Constant.product_resource_id);
        resourceServerSecurityConfigurer.tokenStore(toeknStore()).stateless(true);
    }

    private TokenStore toeknStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }


    private JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(Constant.mySecret);
        jwtAccessTokenConverter.setVerifier(new MacSigner(Constant.mySecret));
        return jwtAccessTokenConverter;
    }

    /**
     * 哪些需要授权，那些不需要授权
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
                .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/product/**").authenticated().anyRequest().permitAll());
    }
}
